﻿using System;
using System.Web.UI;

namespace N2.Details
{
	using Definitions;
	using ComponentModel;
	using Web.UI;
	
	[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
	public class WithEditableUserControlAttribute : EditableUserControlAttribute
	{
		readonly CurrentItemPropertyHolder CurrentItemHolder;

		public WithEditableUserControlAttribute(
			string title,
			string userControlPath,
			string editorPropertyName,
			int sortOrder,
			string name)
			: base(title, userControlPath, editorPropertyName, sortOrder)
		{
			this.Name = name;
			this.CurrentItemHolder = new CurrentItemPropertyHolder();
		}

		public override bool UpdateItem(ContentItem item, Control editor)
		{
			if (editor is IContentItemEditor) {
				return (editor as IContentItemEditor).UpdateItem(item);
			}

			return
				string.IsNullOrEmpty(this.Name)
				//There's hardly any way to know if something inside
				// ContentItem was updated by the editor,
				// so do the positive assert..
					? true
					: base.UpdateItem(item, editor);
		}

		public override void UpdateEditor(ContentItem item, Control editor)
		{
			this.CurrentItemHolder.CurrentItem = item;
			
			if (string.IsNullOrEmpty(this.Name)) {
				//If no ContentItem.<Name> was given,
				// assume that an editor.<editorPropertyName> accepts the whole ContentItem..
				this.SetEditorValue(editor, item);
			} else {
				base.UpdateEditor(item, editor);
			}
		}
	}
}
